package com.alibaba.dubbo.demo.consumer;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import com.alibaba.dubbo.demo.DemoService;
import com.alibaba.dubbo.demo.Student;
import com.alibaba.dubbo.rpc.RpcContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Consumer2 {
	public static void main(String[] args) throws Exception {
        //Prevent to get IPV6 address,this way only work in debug mode
        //But you can pass use -Djava.net.preferIPv4Stack=true,then it work well whether in debug mode or not
        System.setProperty("java.net.preferIPv4Stack", "true");

        //asyncFuture1();
        asyncFuture2();
    }

    public static void asyncFuture1() throws ExecutionException, InterruptedException {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"META-INF/spring/dubbo-demo-consumer.xml"});
        context.start();
        DemoService demoService = (DemoService) context.getBean("demoService2"); // get remote service proxy

        long start = System.currentTimeMillis();

        Student st = new Student();
    	st.setName("zsl");
    	st.setAge(10);
        demoService.sayHello(st);
        Future<String> helloFuture = RpcContext.getContext().getFuture();

        Student st2 = new Student();
    	st2.setName("lisi");
    	st2.setAge(10);
        demoService.sayBye(st2);
        Future<String> byeFuture = RpcContext.getContext().getFuture();

        final String helloStr = helloFuture.get();//消耗5s
        final String byeStr = byeFuture.get();//消耗8s

        System.out.println(helloStr + " -- " + byeStr + " ,cost:" + (System.currentTimeMillis()-start));//总消耗8s
    }

    public static void asyncFuture2() throws ExecutionException, InterruptedException {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"META-INF/spring/dubbo-demo-consumer.xml"});
        context.start();
        DemoService demoService = (DemoService) context.getBean("demoService2"); // get remote service proxy

        long start = System.currentTimeMillis();

        Student st = new Student();
    	st.setName("zsl");
    	st.setAge(10);
        Future<Student> helloFuture = RpcContext.getContext().asyncCall(()-> demoService.sayHello(st));
        
        Student st2 = new Student();
    	st2.setName("lisi");
    	st2.setAge(10);
        Future<Student> byeFuture = RpcContext.getContext().asyncCall(()->demoService.sayBye(st2));

        final Student helloStr = helloFuture.get();//消耗5s
        final Student byeStr = byeFuture.get();//消耗8s

        System.out.println(helloStr + " -- " + byeStr + " ,cost:" + (System.currentTimeMillis()-start));//总消耗8s
    }
}
